<script setup>
import { onMounted, ref } from 'vue';

import { message, notification } from 'ant-design-vue';

import {
  addApi,
  deleteApi,
  listApi,
  updateApi,
  updateModeStatusApi, // 新增状态更新API
} from '#/api/object/tModelConfig.ts';

// 通用 CRUD 钩子
import { crud } from '#/components/crud';

// 初始化搜索表单
const initSearchForm = {
  modelName: '',
  modelKey: '',
  modeStatus: undefined,
};

// 使用 useCrud 管理数据和操作
const {
  dataSource: dataSourceT,
  pagination,
  searchForm,
  selectedRowKeys: rowSelectionSelecRow,
  modalVisible,
  isEditMode,
  formData: currentFormData,
  loadData,
  handleTableChange,
  handleSearch,
  resetSearch,
  deleteSelected: deleteSelect,
  openAddModal: originalOpenAddModal,
  openEditModal: originalOpenEditModal,
  handleSubmit: originalHandleSubmit,
  handleCancel,
} = crud(
  {
    getList: listApi,
    create: addApi,
    update: updateApi,
    delete: deleteApi,
  },
  initSearchForm,
);

// 状态更新加载状态
const loadingStatus = ref({});

// 表格列配置
const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', align: 'center', width: 80 },
  {
    title: '模型名称',
    dataIndex: 'modelName',
    key: 'modelName',
    align: 'center',
  },
  { title: '模型key', dataIndex: 'modelKey', key: 'modelKey', align: 'center' },
  {
    title: '选中状态',
    dataIndex: 'modeStatus',
    key: 'modeStatus',
    align: 'center',
    width: 120,
  },
  {
    title: '操作',
    dataIndex: 'edit',
    key: 'edit',
    align: 'center',
    width: 150,
  },
];

// 行选择配置
const rowSelection = {
  onChange: (selectedRowKeys) => {
    rowSelectionSelecRow.value = selectedRowKeys;
  },
};

// 表单验证规则
const formRules = {
  modelName: [{ required: true, message: '请输入模型名称' }],
  modelKey: [{ required: true, message: '请输入模型key' }],
};

// 重写打开新增模态框方法
const openAddModal = () => {
  originalOpenAddModal();
};

// 重写打开编辑模态框方法
const openEditModal = (record) => {
  originalOpenEditModal(record);
  // 将数字状态转换为布尔值
  currentFormData.value.modeStatus = record.modeStatus;
};

// 重写提交方法
const formRef = ref();
const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    // 将布尔值转换为后端需要的数字格式
    const formData = {
      ...currentFormData.value,
    };

    if (!isEditMode.value) {
      formData.modeStatus = false;
    }

    await originalHandleSubmit(formData);
  } catch {
    // console.log('表单验证失败:', error)
  }
};

// 处理状态切换
const handleStatusChange = async (id, checked) => {
  // 设置加载状态
  loadingStatus.value = { ...loadingStatus.value, [id]: true };

  try {
    // 调用状态更新API
    await updateModeStatusApi({ id }, checked ? 1 : 0);

    notification.success({
      message: '操作成功',
      description: `状态已更新为${checked ? '启用' : '禁用'}`,
    });

    // 局部更新数据，避免重新加载整个表格
    loadData();
  } catch {
    message.error('状态更新失败，请重试');
    // 恢复原状态
    const index = dataSourceT.value.findIndex((item) => item.id === id);
    if (index !== -1) {
      dataSourceT.value[index].modeStatus =
        !dataSourceT.value[index].modeStatus;
    }
  } finally {
    // 取消加载状态
    loadingStatus.value = { ...loadingStatus.value, [id]: false };
  }
};

// 单条删除
const handleDelete = async (id) => {
  try {
    await deleteApi([id]);
    message.success('删除成功');
    loadData();
  } catch {
    message.error('删除失败');
  }
};

// 页面挂载时加载数据
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="padding30px">
    <a-card>
      <!-- 搜索区域 -->
      <a-form
        :model="searchForm"
        layout="inline"
        @submit.prevent="handleSearch"
      >
        <a-form-item label="模型名称">
          <a-input
            v-model:value="searchForm.modelName"
            placeholder="模型名称"
          />
        </a-form-item>
        <a-form-item label="模型key">
          <a-input v-model:value="searchForm.modelKey" placeholder="模型key" />
        </a-form-item>
        <a-form-item label="选中状态">
          <a-select
            v-model:value="searchForm.modeStatus"
            placeholder="请选择状态"
            style="width: 120px"
          >
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button html-type="submit" type="primary">搜索</a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <a-card title="查询列表">
      <!-- 操作按钮 -->
      <a-button
        style="margin-bottom: 16px"
        type="primary"
        @click="openAddModal"
      >
        新增
      </a-button>
      <a-button
        :disabled="rowSelectionSelecRow.length === 0"
        style="margin-left: 16px"
        @click="deleteSelect"
      >
        批量删除
      </a-button>
      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSourceT"
        :pagination="pagination"
        :row-selection="rowSelection"
        :scroll="{ x: true }"
        bordered
        row-key="id"
        @change="handleTableChange"
      >
        <!-- 自定义列渲染 -->
        <template #bodyCell="{ column, record }">
          <!-- 选中状态列 -->
          <template v-if="column.dataIndex === 'modeStatus'">
            <a-switch
              :checked="record.modeStatus"
              :disabled="record.modeStatus"
              :loading="loadingStatus[record.id]"
              @change="(checked) => handleStatusChange(record.id, checked)"
            />
          </template>
          <!-- 操作列 -->
          <template v-if="column.dataIndex === 'edit'">
            <a-button type="link" @click="openEditModal(record)">编辑</a-button>
            <a-popconfirm
              title="确定要删除吗?"
              @confirm="handleDelete(record.id)"
            >
              <a-button danger type="link">删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑模态框 -->
    <a-modal
      :open="modalVisible"
      :title="isEditMode ? '编辑' : '新增'"
      @cancel="handleCancel"
      @ok="handleSubmit"
    >
      <a-form
        ref="formRef"
        :model="currentFormData"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item label="模型名称" name="modelName">
          <a-input
            v-model:value="currentFormData.modelName"
            placeholder="请输入模型名称"
          />
        </a-form-item>
        <a-form-item label="模型key" name="modelKey">
          <a-input
            v-model:value="currentFormData.modelKey"
            placeholder="请输入模型key"
          />
        </a-form-item>
        <!-- <a-form-item label="选中状态" name="modeStatus">
          <a-switch
            v-model:checked="currentFormData.modeStatus"
            :checked-children="`启用`"
            disabled
            :un-checked-children="`禁用`"
          />
        </a-form-item> -->
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.padding30px {
  padding: 20px;
}

:deep(.ant-table-cell) {
  padding: 12px 8px !important;
}
</style>
